<?php

namespace App\Http\Controllers\Base;

use App\Http\Controllers\Controller;
use App\Http\Repository\VideoChannelRepository;
use App\Http\Repository\VideoRepository;
use App\Video;
use App\Http\Services\PicUrlService;
use App\Http\TraitClass\Response;
use Illuminate\Http\Request;

class VideoController extends Controller
{
    use Response;

    private $_repository;

    public function __construct()
    {
        $this->_repository = new VideoRepository();
    }

    /**
     * @param $video_channel_categroy_name
     * @param int $limit
     * @return array
     */
    public function index(Request $request)
    {
        $limit = $request->query('limit', 6);

        $list = $this->_repository->getListByVideoChannelCategoryName(
            $request['video_channel_category_name'],
            $limit);

        $list = $this->returnPage($list);

        //处理字段
        foreach ($list['data']['items'] as $item) {
            $item->pic_url = PicUrlService::getVideoPicUrl($item->pic_url, $item->url);
        }

        return $list;
    }

    /**
     * @param int $channel_id
     * @param int $limit
     * @return array
     */
    public function indexByChannelId(Request $request,int $channel_id)
    {
        $limit = $request->query('limit', 6);

        $list = $this->_repository->getListByChannelId($channel_id, $limit);
        $list = $this->returnPage($list);

        //获取频道名称
        $list['data']['video_channel_name'] = $this->getVideoChannelName($channel_id);

        //处理字段
        foreach ($list['data']['items'] as $item) {
            $item->pic_url = PicUrlService::getVideoPicUrl($item->pic_url, $item->url);
        }

        return $list;
    }

    /**
     * 频道名称
     * @param int $channel_id
     * @return |null
     */
    private function getVideoChannelName(int $channel_id)
    {
        $VideoChannelRepository = new VideoChannelRepository();
        $video_channel = $VideoChannelRepository->show($channel_id);

        if (!$video_channel) {

            return null;
        }

        return $video_channel->name;
    }

    /**
     * @param int $id
     * @return array
     */
    public function show(int $id)
    {
        $result = $this->_repository->show($id);
        if ($result != null) {
            $result = self::showCollection($result);
        }

        return $this->return($result);
    }

    /**
     * @param Video $video
     * @return array
     */
    static public function showCollection(\App\Video $video)
    {
        return [
            'id' => $video->id,
            'name' => $video->name,
            'url' => $video->url,
            'pic_url' => $video->pic_url,
            'video_channel_pic_url' => PicUrlService::getPicUrl($video->videoChannel->pic_url),
            'video_channel_id' => $video->video_channel_id,
            'video_channel_name' => $video->videoChannel->name,
            'updated_at' => $video->updated_at
        ];
    }
}
